<?php
namespace App\Http\Controllers\Api\Buz;

use App\Http\Controllers\Api\BuzBaseController;
use App\Http\Controllers\Controller;
use App\Lib\Code;
use App\Lib\PaymentMap;
use App\Models\RechargeGroupPayment;
use App\Repositories\Criteria\AuthUserCriteria;
use App\Repositories\Eloquent\PlatUserBankRepositoryEloquent;
use App\Repositories\Eloquent\PlatUserProfileEloquent;
use App\Services\ApiResponseService;
use App\Services\PlatUserService;
use App\Validators\Buz\ProfileValidator;
use App\Validators\Buz\RemitBankValidator;
use App\Validators\Buz\PasswordValidator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ProfileController extends Controller
{
    public function createBaseInfo(Request $request,
                                   ProfileValidator $profileValidator,
                                   PlatUserProfileEloquent $platUserProfileEloquent)
    {
            $data = $request->all(array_keys($profileValidator->getRules('create')));
            $profileValidator->with($data)->passesOrFail('create');
            $uid = Auth::user()->id;
            $data += compact('uid');
            $profile = Auth::user()->profile;
            if ($profile) {
                return ApiResponseService::showError(Code::NOTAUTH);
            }
            $platUserProfileEloquent->create($data);
            return ApiResponseService::success(Code::SUCCESS);
    }

    public function createRemitInfo(Request $request,
                           RemitBankValidator $bankValidator,
                           PlatUserBankRepositoryEloquent $bankEloquent)
    {
        $data = $request->all(array_keys($bankValidator->getRules('create')));
        $bankValidator->with($data)->passesOrFail('create');
        $user = Auth::user();
        $uid = $user->id;
        $data += compact('uid') + ['is_default' => 1];
        $bankEloquent->create($data);
        return ApiResponseService::success(Code::SUCCESS);
    }


    public function baseInfo()
    {
        $user = Auth::user();
        $profile = $user->profile()->with(['city' => function ($query) {
            $query->select('id', 'parent', 'name');
        }])->with(['buzScope' => function ($query) {
            $query->select('id', 'parent', 'name');
        }])->first([
            'property', 'role', 'realname', 'idcard',
            'scope', 'enterprise', 'address', 'license',
            'img_id_hand', 'img_id_front', 'img_id_back', 'img_license',
            'img_tax', 'img_permit', 'remark', 'city_id'
        ])->toArray();
        if ($user->status != 2) {
            array_forget($profile, 'remark');
        }
        $profile += ['status' => $user->status];
        $profile['idcard'] = hidePrivateData($profile['idcard']);
        $profile['license'] = hidePrivateData($profile['license']);

        return ApiResponseService::returnData($profile);
    }

    public function remitInfo(PlatUserBankRepositoryEloquent $bankRepositoryEloquent)
    {
        $bankRepositoryEloquent->pushCriteria(AuthUserCriteria::class);
        $bank = $bankRepositoryEloquent->with(['city' => function ($query) {
            $query->select('id', 'parent', 'name');
        }])->first(['id', 'classify', 'username', 'category', 'account', 'city_id', 'branch', 'number']);
        return ApiResponseService::returnData($bank);
    }

    public function loginPwd(Request $request, PasswordValidator $passwordValidator)
    {
        $data = $request->all(array_keys($passwordValidator->getRules('login')));
        $passwordValidator->with($data)->passesOrFail('login');
        $user = Auth::user();
        $old_pwd = $user->password;
        if ( ! password_verify($data['login_pwd'], $old_pwd)) {
            return ApiResponseService::showError(Code::LOGIN_PWD_INVALID);
        }
        $user->password = password_hash($data['new_login_pwd'], PASSWORD_DEFAULT);
        $user->save();
        return ApiResponseService::success(Code::SUCCESS);

    }

    public function tradePwd(Request $request, PasswordValidator $passwordValidator)
    {
        $data = $request->all(array_keys($passwordValidator->getRules('trade')));
        $passwordValidator->with($data)->passesOrFail('trade');
        $user = Auth::user();
        $old_pwd = $user->trade_pwd;
        if ( ! password_verify($data['trade_pwd'], $old_pwd)) {
            return ApiResponseService::showError(Code::TRADE_PWD_INVALID);
        }
        $user->trade_pwd = password_hash($data['new_trade_pwd'], PASSWORD_DEFAULT);
        $user->save();
        return ApiResponseService::success(Code::SUCCESS);
    }

    public function getAssetInfo()
    {
        $assets = Auth::user()->assets;
        return ApiResponseService::returnData([
            'asset' => [
                'available' => number_format($assets->available, 2, '.', ''),
                'recharge_frozen' => number_format($assets->recharge_frozen, 2, '.', ''),
                'withdraw_frozen' => number_format($assets->withdraw_frozen, 2, '.', '')
            ]
        ]);
    }

    public function getPayments(PlatUserService $userService)
    {
        $user = Auth::user();
        $payments = $userService->getPayments($user);
        $data = [];
        foreach ($payments as $payment) {
            $data[] = [
                'rate' => $payment->rate,
                'name' => $payment->payment->name,
                'identify' => $payment->payment->identify,
                'settle_cycle' => $payment->settle_cycle,
                'status' => $payment->status
            ];
        }
        return ApiResponseService::returnData(['payments' => $data]);
    }

    public function viewKey()
    {
        $user = Auth::user();
        $key = $user->key;
        return ApiResponseService::returnData(compact('key'));
    }



}
